<?php

class EventController extends Controller
{

	public function filters()
	{
		return array(
				'accessControl',
		);
	}

	protected function beforeAction($action){
		if(!empty($_GET['username'])){
			/*
			 $member = Member::model()->find("username = :username",array("username"=>$_GET['username']));
			if(empty($member)){
			throw new CHttpException(404, "用户不存在");
			}elseif($member->type == Member::TYPE_GROUP){
			$this->layout = "//layouts/group2";
			}*/
		}else{
			throw new CHttpException(404, "用户不存在");
		}
		return true;
	}

	public function accessRules()
	{
		return array(
				array('allow',
						'actions'=>array('view','list'),
						'users'=>array('*'),
				),
				array("allow",
						'actions'=>array('own','add', 'join','withdraw','users','delete'),
						'users'=>array('@')
				),
				array('deny',
						'users'=>array('*'),
				),
		);
	}

	public function actionIndex()
	{
		$this->render('index');
	}

	public function actionList($username){

		$member = Member::model()->find("username=:username",array("username"=>$username));
		$this->pageTitle = "活动列表 - " .$member->title;
		$criteria=new CDbCriteria;
		$criteria->condition = "t.member_id = :member_id  and event.status>=:status";
		$criteria->params = array("member_id"=>$member->id, "status"=>Event::STATUS_ACTIVE);
		$relations = UserEventRelation::model()->with('event')->findAll($criteria);
		$this->render('list',
				array("relations"=>$relations)
		);
	}
	public function actionOwn($username){
		$member = Member::model()->find("username=:username",array("username"=>$username));
		$this->pageTitle = "创建的活动 - " .$member->title;
		$criteria=new CDbCriteria;
		$criteria->condition='t.status>=:status and t.member_id=:member_id';
		$criteria->params=array(':status'=>Event::STATUS_ACTIVE,'member_id'=>$member->id);
		$events = Event::model()->with('category')->with('member')->findAll($criteria);

		$criteria2=new CDbCriteria;
		$criteria2->condition = "t.member_id = $member->id";
		$relations = UserEventRelation::model()->with('event')->findAll($criteria2);
		$this->render('own',
				array("events"=>$events,"relations"=>$relations)
		);
	}
	public function actionView($id){
		$event=Event::model()->findByPk($id);
		if($event->status < Event::STATUS_ACTIVE){
			throw new CHttpException("404","活动不存在或在审核中");
		}
		$member = Member::model()->findByPk($event->member_id);
		$this->pageTitle = "$event->title - $member->title";
		$this->render("view",array(
				"event"=>$event,
				"relations"=>UserEventRelation::model()->with("member")->findAll("event_id=:event_id",array("event_id"=>$id)),
		));
	}

	public function actionUsers($id){

		header('Content-Type: application/csv;charset=unicode');
		header('Content-Type: application/octet-stream');
		header('Content-Disposition: attachment; filename=file.csv');

		$relations = UserEventRelation::model()->with("member")->findAll("event_id=:event_id",array("event_id"=>$id));
		$data ="";
		foreach ($relations as $relation){
			$member =  $relation->member;
			$link = CHtml::link($member->title,array("event/list","username"=>$relation->member->username));
			//$title = utf8_decode($member->title)
			$data.= "$member->title,$member->gender,$member->email,$member->phone\n";
		}
		echo iconv('utf-8','gb2312',$data);
		exit;
	}
	public function actionDelete($id){
		$event = Event::model()->findByPk($id);
		$member = Member::model()->findByPk($event->member_id);
		if (Utils::isAdmin() || $member->id == Yii::app()->user->id){
			$event = Event::model()->findByPk($id);
			$event ->status = Event::STATUS_DELETED;
			$event->save();
			$this->redirect(array("event/own","username"=>$member->username));
		}
	}

	/**
	 * This method will add the user to this event.
	 * @id	The event id.
	 */
	public function actionJoin($id){
		$relation = UserEventRelation::model()->find("event_id = :event_id and member_id = :member_id",array("event_id"=>$id,"member_id"=>Yii::app()->user->id));
		if(empty($relation)){
			$relation=new UserEventRelation;
			$relation->event_id=$id;
			$relation->member_id=Yii::app()->user->id;
			$relation->type=UserEventRelation::TYPE_PARTICIPANT;
			$relation->joined_time=time();
			$relation->save();
		}
		$event = Event::model()->findByPk($id);
		Yii::app()->user->setFlash("success","谢谢报名 - ".$event->title);
		$this->redirect(array("event/view","id"=>$event->id,"username"=>Yii::app()->user->name));
	}

	public function actionWithdraw($id){
		$relation = UserEventRelation::model()->find("event_id = :event_id and member_id = :member_id",array("event_id"=>$id,"member_id"=>Yii::app()->user->id));
		if($relation->type == UserEventRelation::TYPE_ADMIN){
			Yii::app()->user->setFlash("error","你不能退出自己组织的活动");
			$this->redirect(array("event/view",'id'=>$id,"username"=>Yii::app()->user->name));
		}
		$event = Event::model()->findByPk($relation->event_id);
		$relation->delete();
		Yii::app()->user->setFlash("success","你已经退出了此活动 - ".$event->title);
		$this->redirect(array("event/view","id"=>$event->id,"username"=>Yii::app()->user->name));
	}



	public function actionAdd($id=null){
		//Only the event owner and admin can edit the event
		if(isset($id)){
			if(! (Event::model()->exists("member_id = ".Yii::app()->user->id." and id=$id") || Utils::isAdmin() ) ){
				$this->redirect(array("site/index"));
				CApplication::end();
			}
		}

		//Save event
		if(isset($_POST['Event'])){
			if(empty($_POST['Event']['id'])){
				$event = new Event();
				$event->member_id = Yii::app()->user->id;
				//Init album
				$album = new Album();
				$album->member_id = Yii::app()->user->id;
				$album->save();

				$event->album_id = $album->id;
			}else{
				$event = Event::model()->findByPk($_POST['Event']['id']);
			}
			$event->attributes = $_POST['Event'];

			$event->title = strip_tags($event->title);
			$event->location = strip_tags($event->location);
			$event->content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $event->content);
			$event->start =date("Y-m-d h:i:00", strtotime($event->start));
			$event->end =date("Y-m-d h:i:00", strtotime($event->end));
			$event->status = Event::STATUS_ACTIVE;
			$event->cover=CUploadedFile::getInstance($event,'cover');

			if($event->save()){
				if(!empty($event->cover)){  //upload event front cover image
					$filepath = Utils::getImagePathById("cover", "", $event->id);
					$filepath_thumbnail = Utils::getImagePathById("cover", "thumbnail", $event->id);
					$event->cover->saveAs($filepath);
					ImageUtils::resize($filepath,$filepath,Constants::$size_event_big,Constants::$size_event_big,false);
					ImageUtils::resize($filepath,$filepath_thumbnail,Constants::$size_event_small,Constants::$size_event_small,true);
				}

				if(empty($_POST['Event']['id'])){
					$relation=new UserEventRelation;
					$relation->event_id=$event->id;
					$relation->member_id=Yii::app()->user->id;
					$relation->type=UserEventRelation::TYPE_ADMIN;
					$relation->joined_time=time();
					if(!$relation->save()){
						print_r($relation);
						exit;
					}
				}

				$this->redirect(array("event/view","id"=>$event->id,"username"=>Yii::app()->user->name));
			}else{
				//print_r($event);exit;
				$this->render("add",array("event"=>$event));

				CApplication::end();
			}
		}

		if(!empty($id)){
			$event = Event::model()->findByPk($id);
		}else{
			$event = new Event();
		}
		$this->render("add",array("event"=>$event));
	}
}
